package com.sky.shortlink.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.shortlink.admin.common.biz.user.UserContext;
import com.sky.shortlink.admin.convention.exception.ClientException;
import com.sky.shortlink.admin.dao.entity.UserDO;
import com.sky.shortlink.admin.dao.mapper.UserMapper;
import com.sky.shortlink.admin.dto.req.ShortLinkGroupSaveReqDTO;
import com.sky.shortlink.admin.dto.req.UserLoginReqDTO;
import com.sky.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.sky.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.sky.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.sky.shortlink.admin.dto.resp.UserRespDTO;
import com.sky.shortlink.admin.service.GroupService;
import com.sky.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.sky.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.sky.shortlink.admin.common.enums.UserErrorCodeEnum.*;

/**
 * @author Blue sky
 * @Description 用户接口实现层
 * @create 2024-02-15 16:43
 */

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;   //提供分布式锁
    private final StringRedisTemplate stringRedisTemplate; //保存token
    private final GroupService groupService;

    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        //baseMapper是来自ServiceImpl里的
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            // 抛出给全局异常处理器处理
            throw new ClientException(USER_NULL);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO registerReqDTO) {
        if(hasUsername((registerReqDTO.getUsername())) ){
            throw new ClientException(USER_NAME_EXIST);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerReqDTO, userDO);

        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + registerReqDTO.getUsername());
        if(!lock.tryLock()){ //如果没有取得锁 -- 直接返回
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            //取得锁时 -- 正常操作
            int insert = baseMapper.insert(userDO);
            if(insert < 1){  //插入失败时
                throw new ClientException(USER_SAVE_ERROR);
            }
            userRegisterCachePenetrationBloomFilter.add(registerReqDTO.getUsername());
            groupService.saveGroup(new ShortLinkGroupSaveReqDTO("默认分组"), userDO.getUsername());
        } catch (DuplicateKeyException ex){
            throw new ClientException(USER_EXIST);
        } finally {
            lock.unlock();
        }



    }

    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        // 效验当前用户名是否为登录用户
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, UserContext.getUsername());

        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userUpdateReqDTO,userDO);
        int update = baseMapper.update(userDO, updateWrapper);
        if (update == 0){
            throw new ClientException("您不能修改其他用户的信息");
        }
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO loginReqDTO) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, loginReqDTO.getUsername())
                .eq(UserDO::getPassword, loginReqDTO.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            throw new ClientException(USER_LOGIN_ERROR);
        }
//        //防止重复登录
//        Boolean aBoolean = stringRedisTemplate.hasKey("login_" + loginReqDTO.getUsername());
//        if(aBoolean != null && aBoolean){
//            throw new ClientException(USER_LOGIN_EXIST);
//        }
        //允许多地登录 -- 这是不是第一次登录 返回token -- 用户携带token 可以获取用户相关信息
        Map<Object ,Object> hasLoginMap = stringRedisTemplate.opsForHash().entries("login_" + loginReqDTO.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            //每调一次登录接口就刷新过期时间
            stringRedisTemplate.expire("login_" + loginReqDTO.getUsername(), 30L, TimeUnit.MINUTES);

            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * hash结构
         * key login_username
         *      key uuid
         *      value JSON.toJSONString(userDO)
         */
        //第一次登录 或者 登录过期
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_" + loginReqDTO.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_" + loginReqDTO.getUsername(), 30L, TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean check(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        //判断当前用户是否登录
        if(!check(username, token)){
            throw new ClientException("用户未登录或token不存在");
        }
        stringRedisTemplate.delete("login_" + username);

    }
}
